# -*- coding: utf-8 -*-
# Copyright 2025 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Recipe for uploading uprevs of the baguette image."""

import os
import re
import pathlib
from typing import Generator

from PB.recipes.crosvm.uprev_baguette_image import UprevBaguetteImageProperties
from recipe_engine import post_process
from recipe_engine.recipe_api import RecipeApi
from recipe_engine.recipe_api import StepFailure
from recipe_engine.recipe_test_api import RecipeTestApi
from recipe_engine.recipe_test_api import TestData


DEPS = [
    "recipe_engine/buildbucket",
    "recipe_engine/context",
    "recipe_engine/path",
    "recipe_engine/properties",
    "recipe_engine/step",
    "depot_tools/git",
]

PROPERTIES = UprevBaguetteImageProperties

_PLATFORM2_REPO_URL = "https://chromium.googlesource.com/chromiumos/platform2/"
_UPREV_SCRIPT_PATH = "vm_tools/baguette_image/src/uprev-version-pin.sh"
_VERSION_FILE_PATH = "vm_tools/concierge/baguette_version.h"


def RunSteps(api: RecipeApi, properties: UprevBaguetteImageProperties) -> None:
    # Clone the repo in a temp dir
    checkout = api.path.mkdtemp()
    api.git.checkout(_PLATFORM2_REPO_URL, dir_path=checkout, depth=1)

    with api.context(cwd=checkout):
        # Ensure the commit hook is configured
        api.step(
            "Install commit hook",
            [
                "curl",
                "-Lo",
                ".git/hooks/commit-msg",
                "https://chromium-review.googlesource.com/tools/hooks/commit-msg",
            ],
        )
        api.step("Make commit hook executable", ["chmod", "+x", ".git/hooks/commit-msg"])

        # Run the uprev script
        api.step("Run uprev-image-version.sh", ["bash", _UPREV_SCRIPT_PATH])

        # Check if the uprev made any changes to the version file
        diff_result = api.git("diff", "--exit-codes", "-q", _VERSION_FILE_PATH, ok_ret="any")
        if diff_result.retcode == 0:
            diff_result.presentation.step_text = "Nothing to submit"
            return

        commit_lines = [
            f"vm_tools: Uprev baguette_image version",
            "",
            f"Generated by {api.buildbucket.build_url()}.",
        ]

        # Create a commit with the new version file
        api.git("add", _VERSION_FILE_PATH)
        api.git("commit", "-m", "\n".join(commit_lines))

        # Push the change to gerrit
        if properties.push:
            gerrit_params = ["r=crosvm-uprev@google.com"]
            if properties.bot:
                gerrit_params += ["l=Bot-Commit+1", "l=Commit-Queue+2"]
            else:
                gerrit_params += ["l=Commit-Queue+1"]
            api.git("push", "origin", f"HEAD:refs/for/main%{','.join(gerrit_params)}")


def GenTests(api: RecipeTestApi) -> Generator[TestData, None, None]:
    yield api.test(
        "Submit test uprev",
        api.properties(push=True, bot=False),
        api.step_data("git diff", retcode=1),
    )
    yield api.test(
        "Submit bot uprev",
        api.properties(push=True, bot=True),
        api.step_data("git diff", retcode=1),
    )

    yield api.test(
        "Nothing to submit",
        api.properties(push=True),
        api.step_data("git diff", retcode=0),
    )
